package org.jwos.plugin.file.service.internal;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jcr.RepositoryException;

import org.jwos.platform.domain.GlobalConfig;
import org.jwos.platform.domain.GlobalSession;
import org.jwos.platform.domain.User;
import org.jwos.platform.service.SessionManager;
import org.jwos.platform.service.UserManager;
import org.jwos.plugin.file.dao.FileManagerDAO;
import org.jwos.plugin.file.domain.FileInfo;
import org.jwos.plugin.file.domain.FileUploadInfo;
import org.jwos.plugin.file.domain.FolderInfo;
import org.jwos.plugin.file.domain.FolderType;
import org.jwos.plugin.file.domain.FolderViewInfo;
import org.jwos.plugin.file.domain.PublishedFileInfo;
import org.jwos.plugin.file.domain.SharedFilePermission;
import org.jwos.plugin.file.exception.DuplicateDirectoryException;
import org.jwos.plugin.file.exception.FileException;
import org.jwos.plugin.file.service.FileManager;
import org.jwos.plugin.file.util.MapUtil;
import org.jwos.plugin.file.util.ObservedInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StubFileManager implements FileManager {
	
	private UserManager userManager;

	private SessionManager sessionManager;

	public StubFileManager() {		
	}
	
	@Autowired
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	@Autowired
	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}
	
	public Map login(String sessionId) throws FileException {
		Map result = new HashMap();
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId); 
			if(user!=null) {
				FileManagerDAO dao = new FileManagerDAO();
				if(!dao.isUserRegistered(user.getUserId())) {
					dao.registerUser(user.getUserId());
				}
				
				String currentView = FolderType.FileViewNames[FolderType.FileViewIcons];
				boolean singleUploadMode = false;				
				String view = dao.getUserSetting(user.getUserId(), "currentView");
				if(view!=null) {
					currentView = view;
				}
				String mode = dao.getUserSetting(user.getUserId(), "singleUploadMode");				
				if(mode!=null) {
					singleUploadMode = Boolean.parseBoolean(mode);
				}
				
				result.put("CurrentView", currentView);
				result.put("SingleUploadMode", singleUploadMode);
				result.put("UserName", user.getUserId());
				result.put("FirstName", user.getUserName());
			} else {
				throw new FileException("User not login");
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return result;
	}
	
	public FileInfo getFileInfoById(String sessionId,String fileId) throws FileException {
		FileInfo info = null;
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			String userId = user!=null ? user.getUserId() : null;
			FileManagerDAO dao = new FileManagerDAO();
			info = dao.getFileInfoById(userId,fileId);
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return info;
	}
	
	public InputStream getFileContentById(String sessionId,String fileId) throws FileException {
		InputStream content = null;
		
		try {
			FileManagerDAO dao = new FileManagerDAO();
			if(sessionId!=null) {
				User user = this.sessionManager.getUserBySessionId(sessionId);			
				content = dao.getFileContentById(user.getUserId(),fileId);
			} else {
				content = dao.getFileContentById(null,fileId);
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return content;
	}
	
	public InputStream getFileThumbnailById(String sessionId,String fileId) throws FileException {
		InputStream content = null;
		
		try {
			FileManagerDAO dao = new FileManagerDAO();
			if(sessionId!=null) {
				User user = this.sessionManager.getUserBySessionId(sessionId);			
				content = dao.getFileThumbnailById(user.getUserId(),fileId);
			} else {
				content = dao.getFileThumbnailById(null,fileId);
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return content;
	}
	
	public void createFile(String sessionId,String folderId,String fileName,ObservedInputStream input) 
			throws FileException {		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), folderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify the folder or file.");
			}
			
			if(!isValidFileName(fileName)) {
				throw new FileException("FileManager.error.invalidFileName","File name is invalid.");
			}
			
			dao.createFileNode(user.getUserId(),folderId, fileName, input);
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public void renameFile(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		String fileId = (String)map.get("fileId");
		String name = (String)map.get("name");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), fileId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			if(!isValidFileName(name)) {
				throw new FileException("FileManager.error.invalidFileName","File name is invalid.");
			}
			
			dao.rename(user.getUserId(),fileId, name);
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}		
	}
	
	public Map createFolder(Map map) throws FileException {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		String parentId = (String)map.get("parentId");
		String name = (String)map.get("name");	
		
		try {			
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), parentId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			if(!isValidFolderName(name)) {
				throw new FileException("FileManager.error.invalidFolderName","Folder name is invalid.");
			}
			
			FileInfo folder = dao.createFolderNode(user.getUserId(),parentId, name);
			
			result.put("folderId", folder.getId());
		} catch (RepositoryException e) {
			throw new FileException(e);
		} catch (DuplicateDirectoryException e) {
			throw new FileException(e);			
		}
		
		return result;
	}
	
	public void renameFolder(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		String fileId = (String)map.get("folderId");
		String name = (String)map.get("name");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), fileId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			if(!isValidFolderName(name)) {
				throw new FileException("FileManager.error.invalidFolderName","Folder name is invalid.");
			}
			
			dao.rename(user.getUserId(),fileId, name);
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}		
	}
	
	public Map delete(Map map) throws FileException {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			List folderIds = (List)map.get("folderIds");
			if(folderIds!=null && folderIds.size()>0) {
				for(int i=0;i<folderIds.size();i++) {
					String folderId = (String)folderIds.get(i);
					if(!dao.isFileModifiable(user.getUserId(), folderId)) {
						throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
					}
					
					dao.deleteFolderNodeById(user.getUserId(),folderId);
				}
			}
			
			List fileIds = (List)map.get("fileIds");
			if(fileIds!=null && fileIds.size()>0) {
				for(int i=0;i<fileIds.size();i++) {
					String fileId = (String)fileIds.get(i);
					if(!dao.isFileModifiable(user.getUserId(), fileId)) {
						throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
					}
					
					dao.deleteFileNodeById(user.getUserId(),fileId);
				}
			}
			
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}				
		
		return result;
	}
	
	public void copy(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		List folderIds = (List)map.get("folderIds");
		List fileIds   = (List)map.get("fileIds");
		String targetFolderId = (String)map.get("targetFolderId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), targetFolderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			if(fileIds!=null && fileIds.size()>0) {
				for(int i=0;i<fileIds.size();i++) {
					String fileId = (String)fileIds.get(i);
					dao.copyFileNode(user.getUserId(),fileId, targetFolderId);
				}
			}
			
			if(folderIds!=null && folderIds.size()>0) {
				for(int i=0;i<folderIds.size();i++) {
					String folderId = (String)folderIds.get(i);
					dao.copyFolderNode(user.getUserId(),folderId, targetFolderId);
				}
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public void move(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		List folderIds = (List)map.get("folderIds");
		List fileIds   = (List)map.get("fileIds");
		String targetFolderId = (String)map.get("targetFolderId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), targetFolderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}		
			
			if(fileIds!=null && fileIds.size()>0) {
				for(int i=0;i<fileIds.size();i++) {
					String fileId = (String)fileIds.get(i);
					if(!dao.isFileModifiable(user.getUserId(), fileId)) {
						throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
					}				
				}
			}
			if(folderIds!=null && folderIds.size()>0) {
				for(int i=0;i<folderIds.size();i++) {
					String folderId = (String)folderIds.get(i);
					if(!dao.isFileModifiable(user.getUserId(), folderId)) {
						throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
					}
				}
			}
			
			if(fileIds!=null && fileIds.size()>0) {
				for(int i=0;i<fileIds.size();i++) {
					String fileId = (String)fileIds.get(i);
					dao.moveFileNode(user.getUserId(),fileId, targetFolderId);
				}
			}
			
			if(folderIds!=null && folderIds.size()>0) {
				for(int i=0;i<folderIds.size();i++) {
					String folderId = (String)folderIds.get(i);
					dao.moveFolderNode(user.getUserId(),folderId, targetFolderId);
				}
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public FolderViewInfo getFolderViewById(String sessionId,String folderId) throws FileException {		
		FolderViewInfo view = new FolderViewInfo();
		
		try {
			if(folderId!=null && folderId.trim().length()>0) {
				User user = this.sessionManager.getUserBySessionId(sessionId);			
				FileManagerDAO dao = new FileManagerDAO();
				
				if(folderId.startsWith("SearchResults:")) {
					String keyword = null;
					if(folderId.trim().length()>"SearchResults:".length()) {
						keyword = folderId.substring("SearchResults:".length(),folderId.length()).trim();
					}
					if(keyword!=null && keyword.length()>0) {
						view.setRows(dao.findFileListByKeyword(user.getUserId(), keyword));
					}
					view.setCurrentFolderID(folderId);
					view.setCurrentFolderType(FolderType.SearchResults);
					view.setParentFolderID("");
					view.setCurrentPath(FolderType.FolderNames[FolderType.SearchResults]+":");
				} else {
					FolderInfo folder = dao.getFolderInfoById(user.getUserId(),folderId);	
					
					//check if folder has been deleted
					if(folder==null) {
						FolderViewInfo profile = dao.getUserProfile(user.getUserId());
						String parentId = profile.getParentFolderID(); 
						if(parentId!=null && parentId.trim().length()>0) {
							folderId = parentId;
							folder = dao.getFolderInfoById(user.getUserId(),folderId);
						}
					}
					
					if(folder!=null) {
						view.setCurrentFolderID(folderId);
						view.setCurrentFolderType(folder.getType());
						view.setCurrentPath(dao.getFolderPathById(user.getUserId(),folderId));
						view.setRows(dao.getFileListByFolderId(user.getUserId(),folderId));
						
						FolderInfo parent = dao.getParentFolderInfo(user.getUserId(),folderId);
						if(parent!=null) {
							view.setParentFolderID(parent.getId());
							while(parent!=null) {
								dao.setFolderExpandFlag(user.getUserId(), parent.getId(), true);
								parent = dao.getParentFolderInfo(user.getUserId(), parent.getId());
							}						
						} else {
							view.setParentFolderID("");
						}
						
						String ownerId = dao.getUserIdByItemId(folderId);
						if(!user.getUserId().equals(ownerId)) {
							if(folder.getType()!=FolderType.MyNetwork && folder.getType()!=FolderType.MyNetworkUser) {
								view.setCurrentFolderType(FolderType.SharedFolder);
							}
							view.setCurrentPath(dao.getNetworkFolderPath(user.getUserId(), ownerId, folderId));
							if(view.getRows()!=null && view.getRows().size()>0) {
								for(int i=0;i<view.getRows().size();i++) {
									FileInfo info = (FileInfo)view.getRows().get(i);
									info.setPath(view.getCurrentPath());
								}							
							}
						}
					}
					
					dao.saveUserProfile(user.getUserId(), view);
				}			
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}		
		
		return view;
	}
	
	public List getCompletePathList(Map map) {
		List pathList = new ArrayList();
		
		try {
			String sessionId = (String)map.get("sessionId");
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			pathList = dao.getRecentPathList(user.getUserId());
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		
		return pathList;
	}
	
	public Map getFolderIdByPath(Map map) {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		String path = (String)map.get("path");
		boolean save = Boolean.parseBoolean(map.get("save").toString());
		
		User user = this.sessionManager.getUserBySessionId(sessionId);
		FileManagerDAO dao = new FileManagerDAO();
		String id = dao.getFileItemIdByPath(user.getUserId(), path);
		
		try {
			if(save && id!=null && id.length()>0) {
				String ownerId = dao.getUserIdByItemId(id);
				String realPath = null;
				if(!user.getUserId().equals(ownerId)) {
					realPath = dao.getNetworkFolderPath(user.getUserId(), ownerId, id);					
				} else {
					realPath = dao.getFolderPathById(user.getUserId(), id);
				}				
				List pathList = dao.getRecentPathList(user.getUserId());
				
				boolean exists = false;
				for(int i=0;i<pathList.size();i++) {
					List list = (List)pathList.get(i);
					String p = (String)list.get(1);
					if(p.equals(realPath)) {
						exists = true;
						break;
					}
				}
				
				if(!exists) {
					List list = new ArrayList();
					list.add(id);
					list.add(realPath);
					pathList.add(list);					
				}
				
				if(pathList.size()>20) {
					pathList.remove(0);
				}
				
				if(pathList.size()>0) {
					dao.saveRecentPathList(user.getUserId(), pathList);
					dao.save();
				}
			}
		} catch (RepositoryException e) {
			e.printStackTrace();
		}		
		
		result.put("id", id);
		result.put("path", path);
		
		return result;
	}
	
	public List getSubFoldersByParent(String sessionId,String parentId) throws FileException {
		List folders = new ArrayList();
		
		try {
			FileManagerDAO dao = new FileManagerDAO();
			User user = this.sessionManager.getUserBySessionId(sessionId);
			folders = MapUtil.beanListToMapList(dao.getFolderListByNode(user.getUserId(),true,parentId));
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return folders;
	}
	
	public List getAllFolderTree(String sessionId) throws FileException {
		User user = this.sessionManager.getUserBySessionId(sessionId);
		return this.getAllFolderTreeByUser(user);
	}
	
	public List getAllFolderTreeByUser(User user) throws FileException {
		List folders = new ArrayList();
		
		try {
			FileManagerDAO dao = new FileManagerDAO();
			folders = MapUtil.beanListToMapList(dao.getFolderListByUser(user.getUserId()));
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return folders;
	}	
	
	public void treeNodeCollapse(Map map) {
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			dao.setFolderExpandFlag(user.getUserId(), folderId, false);
			dao.save();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}
	
	public void registerUser(User user) throws FileException {
		try {
			FileManagerDAO dao = new FileManagerDAO();
			dao.registerUser(user.getUserId());
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public Map getSharedItem(Map map) throws FileException {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");
		result.put("folderID", folderId);
		result.put("enabled", false);
		result.put("comment", "");
		result.put("permissions", new ArrayList());
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			FileInfo folder = dao.getFileInfoById(user.getUserId(),folderId);
			if(folder!=null) {
				result.put("enabled", folder.isShared());
				result.put("comment", folder.getDescription()!=null ?folder.getDescription() : "");
				result.put("permissions", dao.getSharedFilePermissions(folderId));
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return result;
	}
	
	public void saveSharedItem(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");
		boolean enabled  = Boolean.parseBoolean(map.get("enabled").toString());
		String comment = (String)map.get("comment");
		List prms = (List)map.get("permissions");
		
		List<SharedFilePermission> permissions = new ArrayList(); 
		if(prms!=null && prms.size()>0) {
			for(int i=0;i<prms.size();i++) {
				Map prmMap = (Map)prms.get(i);
				SharedFilePermission permission = new SharedFilePermission();
				permission.setFolderID(folderId);
				permission.setUserName((String)prmMap.get("userName"));
				permission.setUserAccessType(Integer.parseInt(prmMap.get("userAccessType").toString()));
				permission.setNotify(Boolean.parseBoolean(prmMap.get("notify").toString()));
				permissions.add(permission);
			}
		}
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), folderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			dao.unshareFolder(user.getUserId(),folderId);
			if(enabled) {
				dao.shareFolder(user.getUserId(),folderId, permissions, comment);
			}		
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public Map publishFile(Map map) throws FileException {
		Map result = new HashMap();		
		
		String sessionId = (String)map.get("sessionId");
		String fileId = (String)map.get("fileId");			
		boolean update = Boolean.parseBoolean(map.get("update").toString());

		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();		
			
			if(!dao.isFileModifiable(user.getUserId(), fileId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			PublishedFileInfo pfi = new PublishedFileInfo();		
			if(update) {
				boolean enableExpiration = Boolean.parseBoolean(map.get("enableExpiration").toString());
				String expireDate = (String)map.get("expireDate");
				pfi.setEnableExpiration(enableExpiration);
				pfi.setExpireDate(formatDate(expireDate));
				dao.publishFile(user.getUserId(),fileId,pfi);
				dao.save();
			} else {
				pfi = dao.getPublishedFileInfo(user.getUserId(), fileId);
			}
			
			GlobalConfig config = this.sessionManager.getGlobalConfig();
			String url = config.getCompleteBaseUrl()+"/file/public/download?id="+fileId;
			pfi.setDownloadUrl(url);
			pfi.setDirectUrl(url);
			
			result.put("ReturnValue", pfi);
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
				
		
		return result;
	}
	
	public Map publishFolder(Map map) throws FileException {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");		
		boolean update = Boolean.parseBoolean(map.get("update").toString());		
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();	
			
			if(!dao.isFileModifiable(user.getUserId(), folderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			PublishedFileInfo pfi = new PublishedFileInfo();			
			if(update) {
				boolean enableExpiration = Boolean.parseBoolean(map.get("enableExpiration").toString());
				String expireDate = (String)map.get("expireDate");				
				boolean enablePassword = Boolean.parseBoolean(map.get("enablePassword").toString());		
				String password = (String)map.get("password");
				boolean enableComment = Boolean.parseBoolean(map.get("enableComment").toString());
				String comment = (String)map.get("comment");
				pfi.setEnableExpiration(enableExpiration);
				pfi.setExpireDate(formatDate(expireDate));
				pfi.setEnablePassword(enablePassword);
				pfi.setPassword(password);
				pfi.setEnableComment(enableComment);
				pfi.setComment(comment);
				dao.publishFolder(user.getUserId(),folderId,pfi);
				dao.save();
			} else {
				pfi = dao.getPublishedFileInfo(user.getUserId(), folderId);
			}
			
			GlobalConfig config = this.sessionManager.getGlobalConfig();
			String url = config.getCompleteBaseUrl()+ "/file/public/browse?id="+folderId;
			String rss = config.getCompleteBaseUrl()+ "/file/public/rss?id="+folderId;	
			pfi.setDirectUrl(url);
			pfi.setRssUrl(rss);
			result.put("ReturnValue", pfi);
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return result;
	}
	
	public void unPublishFile(Map map) throws FileException {

		String sessionId = (String)map.get("sessionId");
		String fileId = (String) map.get("fileId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), fileId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			dao.unpublishFile(user.getUserId(),fileId);
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public void unPublishFolder(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			
			if(!dao.isFileModifiable(user.getUserId(), folderId)) {
				throw new FileException("FileManager.error.noModifyRight","You have no right to modify folder or file in this folder.");
			}
			
			dao.unpublishFolder(user.getUserId(), folderId);
			dao.save();
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public List getPublishedFileListByFolderId(String folderId) throws FileException {
		List list = new ArrayList();
		
		try {
			FileManagerDAO dao = new FileManagerDAO();			
			FileInfo folder = dao.getFileInfoById(User.USER_ADMIN, folderId);
			if(folderId!=null) {
				list = dao.getFileListByFolderId(User.USER_ADMIN, folderId);
				if(!folder.isPublished()) {
					FolderInfo parent = dao.getParentFolderInfo(User.USER_ADMIN, folderId);
					FileInfo up = new FileInfo();
					up.setName("..");
					up.setId(parent.getId());
					up.setFolder(true);
					list.add(0, up);
				}				
			}			
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return list;
	}
	
	public boolean isFileInPublishedFolder(String fileId) throws FileException {
		boolean published = false;
		
		try {
			FileManagerDAO dao = new FileManagerDAO();
			published = dao.isFileInPublishedFolder(User.USER_ADMIN, fileId);
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
		
		return published;
	}
	
	public FileInfo getFileProperties(String sessionId,String fileId) {
		FileInfo file = null;
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			file = dao.getFileInfoById(user.getUserId(),fileId);
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		
		return file!=null ? file : new FileInfo();
	}
	
	public FileInfo getFolderProperties(String sessionId,String folderId) {
		FileInfo file = null;
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			file = dao.getFileInfoById(user.getUserId(),folderId);
			file.setSize(dao.getFolderSize(folderId));
			file.setFileCount(dao.getSubFileCount(folderId));
			file.setFolderCount(dao.getSubFolderCount(folderId));
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		
		return file!=null ? file : new FileInfo();
	}
	
	public FileInfo getMultipleItemProperties(String sessionId,String[]fileIds,String[] folderIds) {
		FileInfo info = new FileInfo();	
		long size = 0;
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();		
			if(fileIds!=null) {
				info.setFileCount(fileIds.length);
				for(int i=0;i<fileIds.length;i++) {
					FileInfo file = dao.getFileInfoById(user.getUserId(),fileIds[i]);
					if(file!=null) {
						size += file.getSize();
						info.setPath(file.getPath());
					}
				}
			}
			
			if(folderIds!=null) {
				info.setFolderCount(folderIds.length);
				for(int i=0;i<folderIds.length;i++) {
					FileInfo folder = dao.getFileInfoById(user.getUserId(),folderIds[i]);
					if(folder!=null) {
						size += dao.getFolderSize(folderIds[i]);
						info.setPath(folder.getPath());
					}
				}
			}
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		
		info.setName(info.getFileCount()+" Files, "+info.getFolderCount()+" Folders");
		info.setType("Multiple Types");
		info.setFolder(true);
		info.setShared(true);
		info.setSize(size);
		
		return info;
	}
	
	public void emailFiles(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");		
		List fileIds = (List) map.get("fileIds");
		String to = (String)map.get("to");
		String subject = (String)map.get("subject");
		String body = (String)map.get("body");
		
		try {
			if(fileIds!=null && fileIds.size()>0) {
				FileManagerDAO dao = new FileManagerDAO();
				User user = sessionManager.getUserBySessionId(sessionId);
				
				for(int i=0;i<fileIds.size();i++) {
					String fileId = (String)fileIds.get(i);
					FileInfo file = dao.getFileInfoById(user.getUserId(), fileId);
				}
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	public List getAddressBook(Map map) throws FileException {
		List addresses = new ArrayList();
		return addresses;
	}
	
	public List getSubUsers(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		
		List subUsers = new ArrayList();		
		User currentUser = this.sessionManager.getUserBySessionId(sessionId);
		List users = this.userManager.queryAllUsers();
		if(users!=null && users.size()>0) {
			for(int i =0;i<users.size();i++) {
				User user = (User)users.get(i);				
				if(!user.getUserId().equals(currentUser.getUserId())) {
					List userList = new ArrayList();
					userList.add(user.getUserId());
					userList.add(user.getEmail());
					userList.add(user.getUserName());
					subUsers.add(userList);
				}				
			}
		}
		
		return subUsers;
	}
	
	public Map getUploadObject(Map map) throws FileException {
		Map result = new HashMap();
		
		String sessionId = (String)map.get("sessionId");
		String folderId = (String)map.get("folderId");
		String uploadKey = folderId + System.currentTimeMillis(); 		
		long maxFileSize = FolderType.MaxFileSize;
		long storageLeft = FolderType.MaxStorageSize;
		long bandwidthLeft = FolderType.MaxBandwidthSize;
		
		result.put("UploadKey", uploadKey);
		result.put("FolderID", folderId);
		result.put("MaxFileSize", maxFileSize);
		result.put("StorageLeft", storageLeft);
		result.put("BandwidthLeft", bandwidthLeft);		
		
		return result;
	}
	
	public Map getUploadStatus(Map map) throws FileException {
		Map result = null;
		
		String sessionId = (String)map.get("sessionId");
		String postBackId = (String)map.get("postBackId");
		
		GlobalSession session = this.sessionManager.getGlobalSession(sessionId);
		if(postBackId!=null && session.getAttribute(postBackId)!=null) {
			FileUploadInfo info = (FileUploadInfo)session.getAttribute(postBackId);
			result = new HashMap();
			result.put("returnValue", info.getPercent());
			result.put("description", info.getDescription());
		}
		
		return result;
	}
	
	public void saveFileManagerSetting(Map map) throws FileException {
		String sessionId = (String)map.get("sessionId");
		String key = (String)map.get("key");
		Object value = map.get("value");
		
		try {
			User user = this.sessionManager.getUserBySessionId(sessionId);
			FileManagerDAO dao = new FileManagerDAO();
			if(user!=null && key!=null) {
				dao.saveUserSetting(user.getUserId(), key, value!=null ? value.toString() : null);
			}
		} catch (RepositoryException e) {
			throw new FileException(e);
		}
	}
	
	private boolean isValidFileName(String name) {
		boolean valid = true;
		
		if ((name == null) ||
			(name.indexOf("/") != -1) ||
			(name.indexOf("\\\\") != -1) ||
			(name.indexOf(":") != -1) ||
			(name.indexOf("*") != -1) ||
			(name.indexOf("?") != -1) ||
			(name.indexOf("\"") != -1) ||
			(name.indexOf("<") != -1) ||
			(name.indexOf(">") != -1) ||
			(name.indexOf("|") != -1) ||
			(name.indexOf("&") != -1) ||
			(name.indexOf("[") != -1) ||
			(name.indexOf("]") != -1) ||
			(name.indexOf("'") != -1)) {
			valid = false;
		}
		
		return valid;
	}
	
	private boolean isValidFolderName(String name) {
		boolean valid = true;
		
		if ((name == null) ||
			(name.indexOf("/") != -1) ||
			(name.indexOf("\\\\") != -1) ||
			(name.indexOf(":") != -1) ||
			(name.indexOf("*") != -1) ||
			(name.indexOf("?") != -1) ||
			(name.indexOf("\"") != -1) ||
			(name.indexOf("<") != -1) ||
			(name.indexOf(">") != -1) ||
			(name.indexOf("|") != -1) ||
			(name.indexOf("&") != -1) ||
			(name.indexOf("[") != -1) ||
			(name.indexOf("]") != -1) ||
			(name.indexOf("'") != -1)) {
			valid = false;
		}
		
		return valid;
	}
	
	private String formatDate(String source) {
		String result = null;		
		
		if(source!=null && source.length()>0) {
			try {
				SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat sdfTarget = new SimpleDateFormat("yyyy/MM/dd HH:mm");
				Date date = sdfSource.parse(source);
				result = sdfTarget.format(date);
			} catch (ParseException e) {				
			}			
		} 
		
		return result;
	}
}
